# -*- coding: utf-8 -*-

import logging

from flask import request, has_request_context
from flask.logging import default_handler
import os

from logging.handlers import RotatingFileHandler, TimedRotatingFileHandler
from logging import StreamHandler

from utils.util import CommonUtil

BASE_DIR = os.path.dirname(os.path.abspath(__file__))

LOG_PATH = os.path.join(BASE_DIR, '../logs')

LOG_PATH_ERROR = os.path.join(LOG_PATH, 'error.log')
LOG_PATH_INFO = os.path.join(LOG_PATH, 'info.log')
LOG_PATH_ALL = os.path.join(LOG_PATH, 'all.log')

# 日志文件最大 100MB
LOG_FILE_MAX_BYTES = 100 * 1024 * 1024
# 轮转数量是 10 个
LOG_FILE_BACKUP_COUNT = 10

TRACE_FILTER_ATTR = "trace_filter"


class RequestFormatter(logging.Formatter):
    def format(self, record):
        if has_request_context():
            # record.url = request.url
            try:
                record.trace_id = request.traceid
            except:
                record.trace_id =CommonUtil.get_uuid()
            # record.remote_addr = request.remote_addr
        else:
            # record.url = None
            # record.remote_addr = None
            record.trace_id = None

        return super().format(record)


class Logger(object):

    def init_app(self, app):
        # 移除默认的handler
        app.logger.removeHandler(default_handler)

        formatter = RequestFormatter(
            '%(asctime)s [%(thread)d:%(threadName)s] [TRACE:%(trace_id)s] [%(filename)s:%(module)s:%(funcName)s] '
            '[%(levelname)s]: %(message)s'
        )

        # 将日志输出到文件
        # 1 MB = 1024 * 1024 bytes
        # 此处设置日志文件大小为500MB，超过500MB自动开始写入新的日志文件，历史文件归档
        # file_handler = RotatingFileHandler(
        #     filename=LOG_PATH_ALL,
        #     mode='a',
        #     maxBytes=LOG_FILE_MAX_BYTES,
        #     backupCount=LOG_FILE_BACKUP_COUNT,
        #     encoding='utf-8'
        # )
        # formatter = logging.Formatter(
        #     '%(asctime)s [%(module)s] %(levelname)s session_%(sessionId)-16s %(process)d %(thread)d %(message)s',
        #     '%Y-%m-%d %H:%M:%S')
        file_handler = TimedRotatingFileHandler(filename=LOG_PATH_ALL, when='d', interval=1,
                                                backupCount=15,
                                                encoding="utf8", delay=False)


        file_handler.suffix = "%Y-%m-%d.log"
        file_handler.setFormatter(formatter)
        file_handler.setLevel(logging.INFO)
        stream_handler = StreamHandler()
        stream_handler.setFormatter(formatter)
        stream_handler.setLevel(logging.INFO)

        for logger in (
                # 这里自己还可以添加更多的日志模块，具体请参阅Flask官方文档
                app.logger,
                logging.getLogger('sqlalchemy'),
                logging.getLogger('trace_logger'),
                logging.getLogger('task'),
                # logging.getLogger('spiders.spiders.stock_funds_1'),
                logging.getLogger('web.industry_analysis'),
                logging.getLogger('web.stock_analysis'),
                # logging.getLogger('web.trigger'),
                logging.getLogger('spiders.spiders.middlewares'),
                logging.getLogger('utils.holiday_util'),
                logging.getLogger('service.requests.spider_request')

        ):
            if not logger.handlers:

                logger.setLevel(logging.INFO)
                logger.addHandler(file_handler)
                logger.addHandler(stream_handler)
                logger.info("{}初始化".format(logger.name))

